﻿using Hetang.Models.DataContext;
using Hetang.Models.Classes;
using Hetang.Models.Helper;
using Hetang.Models.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Hetang.Models.Repository
{
    public class LoginRepository : ILoginRepository
    {
        ISessionRepository _sr;

        public LoginRepository() : this(new SessionRepository()) { }

        public LoginRepository(ISessionRepository sr)
        {
            _sr = sr;
        }

        protected Hetang.Models.DataContext.HetangDataContext db = new DataContext.HetangDataContext(DatabaseHelper.GetDatabaseConnect);

        /// <summary>
        /// 检查是否已经登录
        /// </summary>
        /// <returns></returns>
        bool ILoginRepository.CheckLogin()
        {
            if (HttpContext.Current.Session["uid"] != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 获取用户类型
        /// </summary>
        /// <returns>null：未登录，0：管理员，1：个人用户，2：企业用户</returns>
        int ILoginRepository.GetUsertype()
        {
            if (HttpContext.Current.Session["usertype"] == null)
                return -1;
            else
                return Convert.ToInt32(HttpContext.Current.Session["usertype"]);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <returns>返回ok即是成功登录。</returns>
        string ILoginRepository.Login(dt_Login account)
        {
            var ac = db.tbl_Account.FirstOrDefault(a => a.UserName == account.email.Trim());
            if (ac != null)
            {
                if (ac.Password.Equals(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(account.password, "MD5")))
                {
                    _sr.SetLoginSession(ac,true);
                    return "ok";
                }
                else
                {
                    return "密码错误。";
                }
            }
            else
            {
                return "没有这个用户。";
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        void ILoginRepository.Logout()
        {
            //销毁
            System.Web.Security.FormsAuthentication.SignOut();

            //清除所有Cookies
            HttpCookie aCookie;
            string cookieName;
            int limit = HttpContext.Current.Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = HttpContext.Current.Request.Cookies[i].Name;
                aCookie = new HttpCookie(cookieName);
                aCookie.Expires = DateTime.Now.AddYears(-1);
                HttpContext.Current.Response.Cookies.Add(aCookie);
            };

            //清理Session
            _sr.ClearSession();
        }
    }
}